import modelExtend from 'dva-model-extend'
import api from 'api'
import { pageModel } from 'utils/model'
const { pathToRegexp } = require("path-to-regexp")
const { queryAdminContentList, updateAdminContent, createAdminContent,deleteAdminContent,queryAdminContentCategoryTree,queryAdminContentCategoryOptions } = api

export default modelExtend(pageModel, {
  namespace: 'admin_content',

  state: {
    categoryTree: {},
    categoryOptions: {}
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(location => {
        if (pathToRegexp('/admin_content').exec(location.pathname)) {
          //查询文章目录树信
          dispatch({
            type: 'queryCategoryTree'
          })
          dispatch({
            type: 'queryCategoryOptions'
          })
          dispatch({
            type: 'query',
            payload: {
              pageSize: 20,
              page: 1,
              // status: 2,
              ...location.query,
            },
          })
        }
      })
    },
  },

  effects: {
    *query({ payload }, { call, put }) {
      const data = yield call(queryAdminContentList, payload)
      if (data.success) {
        yield put({
          type: 'querySuccess',
          payload: {
            list: data.payload.list,
            pagination: {
              current: Number(payload.pageNum) || 1,
              pageSize: Number(payload.pageSize) || 10,
              total: data.total,
            },
          },
        })
      } else {
        throw data
      }
    },
    //查询同步分类树
    *queryCategoryTree({payload}, {call, put}) {
      const data = yield  call(queryAdminContentCategoryTree)
      if(data.success) {
        yield  put({type: 'updateState', payload: {categoryTree: data.payload}})
      }
    },
    *queryCategoryOptions({payload}, {call,put}) {
      const data = yield call(queryAdminContentCategoryOptions)
      if(data.success) {
        yield put({type: 'updateState', payload: {categoryOptions: data.payload}})
      }
    },
   *create({ payload }, { call, put }) {
      const data = yield call(createAdminContent, payload)
      if (data.success) {
        yield put({ type: 'hideModal' })
      } else {
        throw data
      }
    },

    *update({ payload }, { select, call, put }) {
      // const id = yield select(({ user }) => user.currentItem.id)
      const newUser = { ...payload }
      const data = yield call(updateAdminContent, newUser)
      if (data.success) {
        yield put({ type: 'hideModal' })
      } else {
        throw data
      }
    },
    *delete({ payload }, { select, call, put }) {
      const data = yield call(deleteAdminContent, {ids:payload})
      if (!data.success) {
        throw data
      }
    }
  },
  reducers: {
    showModal(state, { payload }) {
      return { ...state, ...payload, modalVisible: true }
    },

    hideModal(state) {
      return { ...state, modalVisible: false }
    },
  },
})
